package com.itheima.Demo;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Demo2G以上文件的读写 {
    public static void main(String[] args) throws IOException {
        //源文件
        RandomAccessFile f1 = new RandomAccessFile("E\\1.zip","r");
        RandomAccessFile f2 = new RandomAccessFile("D\\2.zip","rw");
        //获取通道
        FileChannel c1 = f1.getChannel();
        FileChannel c2 = f2.getChannel();
        //获取文件大小
        long size = c1.size();
        //每块期望大小
        long every = 500*1024*1024;
        //块数
        int count  = (int)Math.ceil(size*1.0/every);
        //循环
        for (int i = 0; i < count; i++) {
            //每次复制开始位置
            long start = every*i;
            //每次复制实际大小
            long trueSize = size-start<every?size-start:every;
            //映射
            MappedByteBuffer buffer1 = c1.map(FileChannel.MapMode.READ_ONLY, start, trueSize);
            MappedByteBuffer buffer2 = c2.map(FileChannel.MapMode.READ_WRITE, start, trueSize);
            //把m1数组中内容复制到m2数组中
            for(long l=0;l<trueSize;l++){
                buffer2.put(buffer1.get());
            }
        }
        //关闭资源
        c1.close();
        c2.close();
        f2.close();
        f1.close();
    }
}
